/*====================================== 
 author:faxsun
 Copyright © 2015 faxsun. All rights reserved. 
 如需修改请注意与页面标记类名相对应
 数据处理
 author:songdragon 2015-04-29 14:21
 ======================================*/
var showAvatars = function(url, group, elem) {
	$(elem).addClass("shortcut-active").siblings().removeClass(
			"shortcut-active");
	$("#user-avatars").load(url, {
		"group" : group
	}, function() {
		$("#chosenGroup").text(group);
	});
};

var chooseAvatar = function(avatar, elem) {
	$(elem).parent("li").addClass("active").siblings().removeClass("active");
	var arr = avatar.split(".")[0];
	var id = arr.substring(arr.length - 1, arr.length);
	if (arr.substring(arr.length - 2, arr.length - 1).indexOf("/") == -1) {
		id = arr.substring(arr.length - 2, arr.length);
	}
	$("#chosenAvatar").text(id);
};

var modifyAvatar = function(postUrl, returnUrl) {
	$.ajax({
		type : "POST",
		url : postUrl,
		data : {
			"avatar" : $("span[id='chosenAvatar']").text(),
			"group" : $("span[id='chosenGroup']").text()
		},
		success : function(data) {
			window.location.replace(returnUrl);
		}
	});
};

var modifynameFormDisplayed = false;
var showModifyName = function() {
	if (modifynameFormDisplayed) {
		$("#modifyname-form").hide();
		modifynameFormDisplayed = false;
	} else {
		$("#modifyname-form").show();
		modifynameFormDisplayed = true;
	}
};

var modifySignatureFormDisplayed = false;
var showModifySignature = function() {
	if (modifySignatureFormDisplayed) {
		$("#modifySignature-form").hide();
		modifySignatureFormDisplayed = false;
	} else {
		$("#modifySignature-form").show();
		modifySignatureFormDisplayed = true;
	}
};

var modifyName = function(postUrl, returnUrl) {
	$.ajax({
		type : "POST",
		url : postUrl,
		data : {
			"name" : $("input[id='modifyname-input']").val()
		},
		success : function(data) {
			window.location.replace(returnUrl);
		}
	});
};

var modifySignature = function(postUrl, returnUrl) {
	$.ajax({
		type : "POST",
		url : postUrl,
		data : {
			"signature" : $("input[id='modifySignature-input']").val()
		},
		success : function(data) {
			window.location.replace(returnUrl);
		}
	});
};

var checkLoginProcess = function() {
	if ($('#isLogin').length > 0) {
		var isLogin = $('#isLogin').val();
		if (isLogin) {
			// 展示登录框
			$("#trigger-overlay").click()
		}
	}
}

$(function() {
		$('body').on('submit','#loginBox', function(event) {
			event.preventDefault();
			var flag = $(this).validate('submitValidate'); // return boolean;
			if (flag) {
				var username = $('#login_user_email').val();
				var password = $('#login_user_password').val();
				
				var isValid = true;

				$('.valid_message').each(function() {
					isValid = isValid && ($(this).text().length == 0);
				});
				isValid = isValid && password.trim() != "";
				isValid = isValid && username.trim() != "";

				if (!isValid) {
					if (username.trim() == "") {
						$('#login_user_email').focus();
					} else if (password.trim() == "") {
						$('#login_user_password').focus();
					}
					return;
				}
				//若是手机版，则需要显示loading动画
				if(undefined!=$("#login_loading_mobile")){
					$("#login_loading_mobile").css("display" ,"block");
				}
				login(username, password, false);
			}

		});

	$('body').on('click', '#register_btn', function(event) {
		event.preventDefault();
		
		

		var nickname = $('#register_nickname').val();
		var username = $('#register_email').val();
		var password = $('#register_password').val();

		var isValid = true;

		$('.valid_message').each(function() {
			isValid = isValid && ($(this).text().length == 0);
		});
		isValid = isValid && nickname.trim() != "";
		isValid = isValid && password.trim() != "";
		isValid = isValid && username.trim() != "";

		if (!isValid) {
			if (nickname.trim() == "") {
				$('#register_nickname').focus();
			} else if (username.trim() == "") {
				$('#register_email').focus();
			} else if (password.trim() == "") {
				$('#register_password').focus();
			}
			
			return;
		}

		if(!$('#agreement').is(':checked')){
			alert("请阅读并选择同意《范客生活用户协议》!");
			return;
		}
		//若是手机版，则需要显示loading动画
		if(undefined!=$("#login_loading_mobile")){
			$("#login_loading_mobile").css("display" ,"block");
		}


		// 提交到注册controller
		var url = window.location.hostname + ":" + window.location.port;

		/*
		 * if (url == 'localhost' || url.indexOf('192') > -1) { if
		 * (window.location.port == '8080') url += ':8443'; else if
		 * (window.location.port == '21111') { url += ':21112'; } }
		 */
		if (window.location.href.indexOf('faxsun-info-web') > -1) {
			url += '/faxsun-info-web';
		} else if (window.location.href.indexOf('faxsun-info') > -1) {
			url += '/faxsun-info';
		}

		url = 'http://' + url + '/reg';
		$.post(url, {
			"username" : username,
			"password" : password,
			"name" : nickname
		}).done(function(data) {

			if (data.code < 0) {
				//若手机登录失败则去除loading动画遮罩层
				if(undefined!=$("#login_loading_mobile")){
					$("#login_loading_mobile").css("display" ,"none");
				}
				alert(data.message);
			} else {
				alert("注册成功");
				// 替换login区域
				login(username, password, true);
			}
		});

	});

	// 注销
	$('body').on('click', '.logout-icon', function(event) {
		// 改为服务器端通知地址
		var url = window.location.hostname + ":" + window.location.port;
		if (window.location.href.indexOf('faxsun-info') > -1) {
			url += '/faxsun-info';
		} else if (window.location.href.indexOf('faxsun-info-web') > -1) {
			url += '/faxsun-info-web';
		}
		url = 'http://' + url + '/logout';
		$.get(url).done(function(data) {
			// if(data.retCode==0)
			var curr = location.href;
			if (curr.indexOf('post/add') > -1 || curr.indexOf('/users/') > -1) {
				location.href = "/faxsun-info";
			} else {
				location.reload();
			}
		});
	});

	function login(username, password, isSlient) {
		var url = window.location.hostname + ":" + window.location.port;
		/*
		 * 
		 * if (url == 'localhost' || url.indexOf('192') > -1) { if
		 * (window.location.port == '8080') url += ':8443'; else if
		 * (window.location.port == '21111') { url += ':21112'; } }
		 */
		if (window.location.href.indexOf('faxsun-info-web') > -1) {
			url += '/faxsun-info-web';
		} else if (window.location.href.indexOf('faxsun-info') > -1) {
			url += '/faxsun-info';
		}

		url = 'http://' + url + '/login';

		$.ajax({
			url : url,
			method : "POST",
			data : {
				"username" : username,
				"password" : password
			}
		}).done(function(data) {
			// alert(data);
			// 提示登陆成功
			// 关闭登陆模式窗口
			if (data.retCode == 0) {
				// 登陆成功
				// 替换login区域
				if ($('#isLogin').length > 0) {
					// 登录中间页
					var isLogin = $('#isLogin').val();
					// console.log(isLogin);
					if (isLogin) {
						location.href = $('#redirectUrl').val();
					}
				} else {
					// refresh current page
					location.reload();
				}
				/*
				 * var loginBox = $(".log-box"); if ($('.logout-panel').length <=
				 * 0) { $(".login-panel").remove(); var userUrl = "/users/" +
				 * data.user.id; if (window.location.href
				 * .indexOf('faxsun-info') > -1) { userUrl = "/faxsun-info" +
				 * userUrl; } var template = "<div class='logout-panel'>" + "<a
				 * href='" + userUrl + "'>" + data.user.name + "</a><span
				 * class='logout-icon'>" "</span></div>";
				 * loginBox.append(template); // 关闭登陆框 $("#logBox
				 * .overlay-close").click(); }
				 */
			} else {
				// 登陆失败
				if (!isSlient) {
					//登录失败则去除loading动画遮罩层
					if(undefined!=$("#login_loading_mobile")){
						$("#login_loading_mobile").css("display" ,"none");
					}
					if (data.message !== 'undefined') {
						alert(data.message);
					} else {
						alert("网络或服务器错误，请稍后再试!");
					}
				}
			}
		});

	}

	// 检查是否为登录中间页功能
	checkLoginProcess();
});
